﻿using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using com.tdb.foundation;
using DG.Tweening;
using Script;
using Script.Function.Posion.Data;
using UnityEngine;

public class HandStackView : MonoBehaviour
{
    private const int CardWidth = 250;

    private const int MinCardShowWidth = 100;
    /// <summary>
    /// 用来模拟发牌路线的长度
    /// </summary>
    private const int MoveForDealSim = 200;
    //private GameObject _cardPrefab;
    
    private List<CardItemView> _cards;

    private void Awake()
    {
        _cards = new List<CardItemView>();
    }

    private void Start()
    {
        StartCoroutine(GenCard());
    }

    IEnumerator GenCard()
    {
        while (_cards.Count < 12)
        {
            AddCard(new CardData(CardColorType.Posion, _cards.Count%10));
            RefreshCardsPostion();
            yield return new WaitForSeconds(.3f);
        }
    }
    
    public void AddCard(CardData card)
    {
        var newCard = Instantiate(Singleton<GameResManager>.Instance.Load<GameObject>(PrefabPath.CardItemView));
        var cardItemView = newCard.GetComponent<CardItemView>();
        cardItemView.Init(_cards.Count, card);
        _cards.Add(cardItemView);
        newCard.transform.SetParent(transform, false);
        float newCardX = ((_cards.Count - 1) * MinCardShowWidth) / 2f + MoveForDealSim;
        newCard.GetComponent<RectTransform>().anchoredPosition = new Vector2(newCardX,0);
        
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Q))
        {
            RemoveCard(_cards.Count/2);
        }
    }

    public void RemoveCard(int index)
    {
        var target = _cards[index];
        _cards.RemoveAt(index);
        Destroy(target.gameObject);
        RefreshCardsPostion();
    }

    private void RefreshCardsPostion()
    {
        if (_cards == null || _cards.Count == 0) return;
        float totalWidth = (_cards.Count - 1) * MinCardShowWidth;
        float leftPostion = -(totalWidth / 2);
        for (int i = 0; i < _cards.Count; i++)
        {
            var card = _cards[i];
            card.gameObject.GetComponent<RectTransform>().DOAnchorPosX(leftPostion + i * MinCardShowWidth, .5f,true);
        }
    }

}
